import { Injectable } from '@nestjs/common';
import { CreateProjectDto } from './dto/create-project.dto';
import { UpdateProjectDto } from './dto/update-project.dto';
import {InjectRepository} from "@nestjs/typeorm";
import {ProjectEntity} from "./entities/project.entity";
import {Repository} from "typeorm";
import {ResultData} from "../../common/utils/result";
import {QueryDeepPartialEntity} from "typeorm/query-builder/QueryPartialEntity";
import QueryProjectDto from "./dto/query-projects.dto";

@Injectable()
export class ProjectsService {
  constructor(
      @InjectRepository(ProjectEntity)
      private readonly projectEntityRepo: Repository<ProjectEntity>,
  ) {
  }
  async create(createProjectDto: CreateProjectDto) {
    const res = await this.projectEntityRepo.save(createProjectDto);
    if(!res) return ResultData.fail(500,'添加失败',null)
    return ResultData.ok(null,'添加成功')
  }

  async findAll(queryProjectsDto: QueryProjectDto) {
    const res = await this.projectEntityRepo.find({
      where:[
        {
          comment: queryProjectsDto.key,
        },
        {
          name: queryProjectsDto.key,
        },
      ],
      order:{
        createDate: 'DESC'
      }
    })
    if(!res) return ResultData.fail(500,'获取失败',null)
    return ResultData.ok(res,'获取成功')
  }

  async findList(queryProjectsDto: QueryProjectDto) {
    const res = await this.projectEntityRepo.createQueryBuilder('projects').addOrderBy('create_date','DESC').limit(5).getMany()
    if(!res) return ResultData.fail(500,'获取失败',null)
    return ResultData.ok(res,'获取成功')
  }

  findOne(id: number) {
    return `This action returns a #${id} project`;
  }

  async update(updateProjectDto: UpdateProjectDto) {
    const updateRes = await this.projectEntityRepo.update({id: updateProjectDto.id},updateProjectDto as QueryDeepPartialEntity<ProjectEntity>);
    if(!updateRes) return ResultData.fail(500,'更新失败',null)
    return ResultData.ok(null,'更新成功')
  }

  async remove(id: number) {
    const delRes =await this.projectEntityRepo.delete({id})
    if(!delRes) return ResultData.fail(500,'删除失败',null)
    return ResultData.ok(null,'删除成功')
  }
}
